package com.hwadee.ems.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.hwadee.ems.domain.dto.Result;
import com.hwadee.ems.domain.dto.PageQuery;
import com.hwadee.ems.domain.po.Class;
import com.hwadee.ems.domain.vo.ClassVO;
import com.hwadee.ems.service.IClassService;

/**
 * <p>
 * 班级 前端控制器
 * </p>
 *
 * @author EnosElinsa
 * @since 2024/06/21
 */
@Slf4j
@RestController
@RequestMapping("/class")
public class ClassController {

    @Resource
    private IClassService classService;

    @GetMapping("/page")
    public Result<IPage<ClassVO>> page(PageQuery pageQuery, ClassVO classVO) {
        return classService.page(pageQuery, classVO);
    }

    @PostMapping
    public Result<Long> save(@RequestBody Class classEntity) {
        if (classService.save(classEntity)) {
            log.info("save class success, classId: {}", classEntity.getId());
            return Result.ok(classEntity.getId());
        } else {
            log.error("save class failed, classEntity: {}", classEntity);
            return Result.error();
        }
    }

    @PutMapping
    public Result<Void> updateById(@RequestBody Class classEntity) {
        if (classService.updateById(classEntity)) {
            log.info("update class success, classId: {}", classEntity.getId());
            return Result.ok();
        } else {
            log.error("update class failed, classEntity: {}", classEntity);
            return Result.error();
        }
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> removeById(@PathVariable Long id) {
        if (classService.removeById(id)) {
            log.info("remove class success, classId: {}", id);
            return Result.ok();
        } else {
            log.error("remove class failed, classId: {}", id);
            return Result.error();
        }
    }

    @GetMapping("/list")
    public Result<List<ClassVO>> list() {
        return Result.ok(
            classService.list()
               .stream()
               .map(ClassVO::new)
               .collect(Collectors.toList())
        );
    }
    
}
